package com.study.server.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.study.server.domain.Chapter;
import com.study.server.domain.ChapterExample;
import com.study.server.dto.ChapterDto;
import com.study.server.dto.PageDto;
import com.study.server.mapper.ChapterMapper;
import com.study.server.util.CopyUtil;
import com.study.server.util.UuidUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class ChapterService {

    @Resource
   private ChapterMapper mapper;


    public String queryAll(){
        return "";
    };

    /**
     * 查询操作
     * @param chapterPageDto
     */
    public void list(PageDto<Chapter> chapterPageDto){

        Page<Object> objects = PageHelper.startPage(chapterPageDto.getPage(),chapterPageDto.getSize());
        ChapterExample chapterExample = new ChapterExample();
        //      chapterExample.createCriteria().andIdEqualTo("1");
    //   chapterExample.setOrderByClause("id desc");
        List<Chapter> chapterList = mapper.selectByExample(chapterExample);

        PageInfo<Chapter> chapterPageInfo = new PageInfo<>(chapterList);
        chapterPageDto.setTotal(chapterPageInfo.getTotal());
        List<ChapterDto> chapterDtoList = new ArrayList<ChapterDto>();
        for (int i = 0; i <chapterList.size() ; i++) {
            Chapter chapter = chapterList.get(i);
            ChapterDto dto = new ChapterDto();
            BeanUtils.copyProperties(chapter,dto);
            chapterDtoList.add(dto);
        }
        chapterPageDto.setList(chapterList);

    };

    /**
     * 删除或新增
     * @param chapterDto
     */

    public void save(ChapterDto chapterDto){
        Chapter chapter  = CopyUtil.copy(chapterDto,Chapter.class);
        if(StringUtils.isEmpty(chapter.getId())){
          this.insert(chapter);
      }else {
            this.update(chapter);
      }
    }

    /**
     * 新增
     * @param chapter
     */

    private void insert(Chapter chapter){
        chapter.setId(UuidUtil.getShortUuid());
        mapper.insert( chapter );
    }
    private void update(Chapter chapter){
        mapper.updateByPrimaryKey(chapter);
    }

    /**
     * 删除
     * @param id
     */
    public void del(String id){
        mapper.deleteByPrimaryKey(id);
    }

}
